import { defineStore } from 'pinia'
import http from '../utils/http'

export const useSalesStore = defineStore('sales', {
  state: () => ({
    sales: [],
    statistics: null,
    ranking: null,
    loading: false,
    error: null
  }),
  
  getters: {
    getSales: (state) => state.sales,
    getStatistics: (state) => state.statistics,
    getRanking: (state) => state.ranking,
    isLoading: (state) => state.loading
  },
  
  actions: {
    async fetchSales(params = {}) {
      this.loading = true
      try {
        const response = await http.get('/sales', { params })
        this.sales = response
        this.error = null
        return { success: true, data: response }
      } catch (error) {
        this.error = error.response?.data?.message || '获取销售记录失败'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },
    
    async fetchStatistics(params = {}) {
      this.loading = true
      try {
        const response = await http.get('/sales/statistics', { params })
        this.statistics = response
        this.error = null
        return { success: true, data: response }
      } catch (error) {
        this.error = error.response?.data?.message || '获取销售统计失败'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },
    
    async fetchRanking(params = {}) {
      this.loading = true
      try {
        const response = await http.get('/sales/ranking', { params })
        this.ranking = response
        this.error = null
        return { success: true, data: response }
      } catch (error) {
        this.error = error.response?.data?.message || '获取销售排行失败'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    },
    
    async createSale(saleData) {
      this.loading = true
      try {
        const response = await http.post('/sales', saleData)
        // 更新销售列表
        this.sales.unshift(response.sale)
        this.error = null
        return { success: true, data: response }
      } catch (error) {
        this.error = error.response?.data?.message || '创建销售记录失败'
        return { success: false, message: this.error }
      } finally {
        this.loading = false
      }
    }
  }
})